const ejs = require("ejs");
const path = require("path");
const fs = require("fs");

/**
 * 解析ejs模板
 * @param {*} temp ejs模板
 * @param {*} data 模板数据
 * @returns
 */
const compile = (temp, data) => {
  const tempPath = path.resolve(__dirname, `../templates/${temp}`);
  return new Promise((resolve, reject) => {
    ejs.renderFile(tempPath, { data }, {}, (err, result) => {
      if (err) {
        console.log(err);
        reject();
      }
      resolve(result);
    });
  });
};

/**
 * 判断路径是否存在 若不存在递归生产路径
 * @param {*} pathName
 * @returns
 */
const createDirSync = (pathName) => {
  if (fs.existsSync(pathName)) {
    return true;
  } else {
    if (createDirSync(path.dirname(pathName))) {
      fs.mkdirSync(pathName);
      return true;
    }
  }
};

/**
 * 根据文件路径与内容写入文件
 * @param {*} pathName 文件路径
 * @param {*} content 内容
 */
const writeToFile = (pathName, content) => {
  fs.promises.writeFile(pathName, content);
};

module.exports = {
  compile,
  writeToFile,
  createDirSync,
};
